package List;

import java.util.ArrayList;
import java.util.List;

/**
 * 234.回文链表
 * 给你一个单链表的头节点 head ，请你判断该链表是否为回文链表。如果是，返回 true ；否则，返回 false 。
 */
public class isPalindrome {
    /**
     * hot100一刷
     * hot100二刷
     */
    public boolean isPalindrome(ListNode head) {
        if (head.next == null)
            return true;
        List<Integer> list = new ArrayList<>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }

        Object[] arr = list.toArray();
        for (int l = 0, r = arr.length - 1; l <= r; l++, r--) {
            if (arr[l] != arr[r])
                return false;
        }
        return true;
    }


    class Solution {
        public boolean isPalindrome(ListNode head) {
            ListNode mid = middleNode(head);
            ListNode head2 = reverseList(mid);
            while (head2 != null) {
                if (head.val != head2.val) { // 不是回文链表
                    return false;
                }
                head = head.next;
                head2 = head2.next;
            }
            return true;
        }

        // 876. 链表的中间结点
        private ListNode middleNode(ListNode head) {
            ListNode slow = head;
            ListNode fast = head;
            while (fast != null && fast.next != null) {
                slow = slow.next;
                fast = fast.next.next;
            }
            return slow;
        }

        // 206. 反转链表
        private ListNode reverseList(ListNode head) {
            ListNode pre = null;
            ListNode cur = head;
            while (cur != null) {
                ListNode nxt = cur.next;
                cur.next = pre;
                pre = cur;
                cur = nxt;
            }
            return pre;
        }
    }
}
